package com.hackerrank.contests.aug13.challenges.kthancestor;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Solution {
	private static class Node {
		int v;
		Node p;
		public Node(int v) {
			this.v = v;
		}
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int T = in.nextInt();
		for(int t = 0; t < T; t++) {
			int P = in.nextInt();
			Map<Integer, Node> m = new HashMap<Integer, Node>();
			for(int i = 0; i < P; i++) {
				int X = in.nextInt(), Y = in.nextInt();
				Node nx = m.get(X);
				if(nx == null) {
					nx = new Node(X);
					m.put(X, nx);
				}
				Node ny = m.get(Y);
				if(ny == null) {
					ny = new Node(Y);
					m.put(Y, ny);
				}
				nx.p = ny;
			}
			int Q = in.nextInt();
			for(int i = 0; i < Q; i++) {
				int q = in.nextInt(), X = in.nextInt();
				switch(q) {
				case 0:
					int Y = in.nextInt();
					Node nx = m.get(X), ny = m.get(Y);
					if(ny == null) {
						ny = new Node(Y);
						m.put(Y, ny);
					}
					ny.p = nx;
					break;
				case 1:
					m.remove(X);
					break;
				case 2:
					int K = in.nextInt();
					Node p = m.get(X);
					for(int j = 0; p != null && j < K; j++)
						p = p.p;
					if(p == null)
						System.out.println(0);
					else
						System.out.println(p.v);
					break;
				}
			}
		}
	}
}
